package com.renwei.yunlong.activity.news;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.DisplayUserInfoActivity;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.GroupChatBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.event.ChatMemberRefreshEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.view.RoundView;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

import static com.renwei.yunlong.R.id.tv_edit;

public class GroupMemberActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {

    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(tv_edit)
    TextView tvEdit;
    @Bind(R.id.iv_cont)
    ImageView ivCont;
    @Bind(R.id.iv_edit)
    ImageView ivEdit;
    @Bind(R.id.iv_contacts)
    ImageView ivContacts;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.iv_scroll)
    ImageView ivScroll;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    private MemberAdapter adapter;
    private String groupId;
    private GroupChatBean bean;

    public static void OpenActivity(Context context, String groupId) {
        Intent intent = new Intent(context, GroupMemberActivity.class);
        intent.putExtra("groupId", groupId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_member);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);
        ivBack.setVisibility(View.VISIBLE);
        tvTitle.setText("群成员");
        ivCont.setImageResource(R.mipmap.icon_edit);
        ivEdit.setVisibility(View.VISIBLE);
        ivEdit.setImageResource(R.mipmap.plus);
        tvEdit.setText("移除");
        tvEdit.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        ivCont.setOnClickListener(this);
        ivEdit.setOnClickListener(this);
        groupId = getIntent().getStringExtra("groupId");
        adapter = new MemberAdapter(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                if (adapter.isCheck()) {
                    if ("0".equals(adapter.getData().get(position).getIsMainGroup())) {
                        Boolean b = adapter.getIsChecks().get(position);
                        adapter.getIsChecks().set(position, !b);
                        adapter.notifyMyItemChanged(position);
                    }
                } else {
                    if ("1".equals(companyType)) {
                        DisplayUserInfoActivity.OpenActivity(mContext, adapter.getItem(position).getEmployeeId(),
                                adapter.getItem(position).getSourceFlag());
                    } else {
                        DisplayUserInfoActivity.OpenActivity(mContext, adapter.getItem(position).getEmployeeId(),
                                "1".equals(adapter.getItem(position).getSourceFlag()) ? "0" : "1");
                    }
                }
            }
        });
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefreshMember(ChatListCloseEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppHelper.clearCheckList();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        manager.getChatGroupMember(this, groupId, this);
    }

    private void setData(List<Contact> rows) {
        String empId = "";
        if ("1".equals(companyType)) {
            empId = ownerBean.getRows().getUserName();
        } else if ("2".equals(companyType)) {
            empId = serviceLoginBean.getRows().getUserName();
        }
        for (Contact row : rows) {
            if (empId.equals(row.getMobilePhone()) && "1".equals(row.getIsMainGroup())) {
                ivCont.setVisibility(View.VISIBLE);
                break;
            } else {
                ivCont.setVisibility(View.GONE);
            }
        }
        adapter.setData(rows);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cont:
                if (adapter != null) {
                    List<Boolean> list = new ArrayList<>();
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        list.add(false);
                    }
                    adapter.openDeleteState(list);
                    ivCont.setVisibility(View.GONE);
                    ivEdit.setVisibility(View.GONE);
                    tvEdit.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_edit:
                // 添加群成员
                StartChatActivity.openActivity(mContext, groupId);
                break;
            case R.id.tv_edit:
                List<Boolean> isChecks = adapter.getIsChecks();
                if (isChecks != null && isChecks.size() > 0) {
                    for (int i = 0; i < isChecks.size(); i++) {
                        if (isChecks.get(i)) {
                            deleteMember(isChecks);
                            adapter.closeDeleteState();
                            break;
                        } else if (i == isChecks.size() - 1) {
                            showCenterInfoMsg("请选择要移除的群成员");
                        }
                    }
                }
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    private void deleteMember(final List<Boolean> isChecks) {

        String employeeId = "";
        for (int i = 0; i < adapter.getData().size(); i++) {
            if (isChecks.get(i)) {
                employeeId += adapter.getData().get(i).getEmployeeId() + ",";
                continue;
            }
        }
        employeeId = employeeId.substring(0, employeeId.length() - 1);

        HashMap<String, String> map = new HashMap<>();
        map.put("groupId", groupId);
        map.put("employeeId", employeeId);
        ServiceRequestManager.getManager().exitChatGroup(this, JsonMapUtil.mapToJson(map), this);

    }

    @Override
    public void onBackPressed() {
        if (adapter == null) {
            AppHelper.clearCheckList();// : 2017/12/13 返回的时候清空选中列表
            super.onBackPressed();
        } else if (adapter.isCheck()) {
            adapter.closeDeleteState();
            ivCont.setVisibility(View.VISIBLE);
            ivEdit.setVisibility(View.VISIBLE);
            tvEdit.setVisibility(View.GONE);
        } else {
            AppHelper.clearCheckList();// : 2017/12/13 返回的时候清空选中列表
            finish();
        }

    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                bean = new Gson().fromJson(result, GroupChatBean.class);
                if (bean.getMessage().getCode() == 200) {
                    if (bean.getRows() != null) {
                        setData(bean.getRows());
                    }
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            case 2: //删除人员
                GroupChatBean groupChatBean = new Gson().fromJson(result, GroupChatBean.class);
                if (groupChatBean.getMessage().getCode() == 200) {
                    ivCont.setVisibility(View.VISIBLE);
                    ivEdit.setVisibility(View.VISIBLE);
                    tvEdit.setVisibility(View.GONE);
                    for (int i = adapter.getIsChecks().size() - 1; i >= 0; i--) {
                        if (adapter.getIsChecks().get(i)) {
                            AppHelper.deleteGroupMember(adapter.getItem(i).getEmployeeId());
                            adapter.removeData(i);
                        }
                    }
                    EventBus.getDefault().post(new ChatMemberRefreshEvent());
                } else {
                    showCenterInfoMsg(groupChatBean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();// : 2017/12/12 此处不能删除否则无法清空里面已经选中的群成员
//        if (bean != null && bean.getRows() != null) {
//            setData(bean.getRows());
//        }
    }

    @Override
    public void onException(int requestId, String code) {
        LogUtil.e(code);
    }

    class MemberAdapter extends BaseRecyclerViewAdapter<Contact> {

        private boolean check;
        private List<Boolean> isChecks;

        public MemberAdapter(Context context) {
            super(context);
        }


        public boolean isCheck() {
            return check;
        }

        public List<Boolean> getIsChecks() {
            return isChecks;
        }

        public void openDeleteState(List<Boolean> isChecks) {
            this.isChecks = isChecks;
            check = true;
            notifyDataSetChanged();
        }

        public void closeDeleteState() {
            check = false;
            notifyDataSetChanged();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = inflater.inflate(R.layout.item_group_item_list, parent, false);
            return new MemberHolder(inflate);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            Contact item = getItem(position);
            MemberHolder mHolder = (MemberHolder) holder;
            if (item != null) {
                mHolder.catalog.setVisibility(View.GONE);
                mHolder.title.setText(item.getUserName());
                String avatar = "";// : 2017/12/10 防止第二次点击的时候再次添加前缀导致图片不显示
                if (!StringUtils.value(item.getAvatar()).startsWith("http")) {
                    if ("1".equals(item.getSourceFlag())) {
                        avatar = Api.$().SERVICE_FILE_URL + StringUtils.value(item.getAvatar());
                    } else {
                        avatar = Api.$().OWNER_FILE_URL + StringUtils.value(item.getAvatar());
                    }
                } else {
                    avatar = item.getAvatar();
                }
                //将群组列表中成员保存到 底部列表数据中
                Glide.with(mContext).load(avatar).placeholder(R.mipmap.icon_header_default).error(R.mipmap.icon_header_default).into(mHolder.rvPic);
                item.setAvatar(avatar);
                AppHelper.setGroupMember(item);
                if ("1".equals(item.getIsMainGroup())) {
                    mHolder.tvQunzhu.setVisibility(View.VISIBLE);
                } else {
                    mHolder.tvQunzhu.setVisibility(View.GONE);
                }
                if (check && "0".equals(item.getIsMainGroup())) { // 删除状态
                    mHolder.ivCb.setVisibility(View.VISIBLE);
                    if (isChecks != null) {
                        if (isChecks.get(position)) {
                            mHolder.ivCb.setImageResource(R.mipmap.icon_regist_cb_pre);
                        } else {
                            mHolder.ivCb.setImageResource(R.mipmap.icon_regist_cb_nor);
                        }
                    }
                } else {
                    mHolder.ivCb.setVisibility(View.GONE);
                }
            }
            mHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickLitener.onItemClick(v, position);
                }
            });
        }

    }

    class MemberHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.tv_letter)
        TextView catalog;
        @Bind(R.id.iv_cb)
        ImageView ivCb;
        @Bind(R.id.rv_header)
        RoundView rvPic;
        @Bind(R.id.tv_name)
        TextView title;
        @Bind(R.id.tv_department)
        TextView bbb;
        @Bind(R.id.tv_group)
        TextView ccc;
        @Bind(R.id.tv_qunzhu)
        TextView tvQunzhu;

        public MemberHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}
